    //
//  PhotoUploadViewController.m
//  Tagged
//
//  Created by Dalei Li on 4/14/10.
//  Copyright 2010 Tagged. All rights reserved.
//

#import "PhotoUploadViewController.h"
/*****
#import "TaggedUtility.h"
#import "TaggedAsyncConnection.h"
*****/
@implementation PhotoUploadViewController
/***
@synthesize timer,navItem,progressView,selectImage, mainImageView, captionTextField, viewMovedUp, activityIndicator, delegate, caption, appDelegate, uploadResult, uploadConnection;
****/
/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

/********
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navItem.titleView = nil;
	self.navItem.title = NSLocalizedString(@"Upload",@"photo upload");  
	caption = [[NSString alloc] init];
    uploadResult = [[NSMutableDictionary alloc] init];
    
    uploadConnection = [[TaggedAsyncConnection alloc] init];
    self.uploadConnection.asyncType = TaggedAsyncConnectionTypePhotoUpload;
}
-(void)startProgressBarRun 
{
	self.timer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(updateProgressBar) userInfo:nil repeats:YES];

}
-(void)updateProgressBar
{
	if (self.progressView.progress < 0.85) 
	{
		self.progressView.progress = self.progressView.progress+0.01;
	}
	else 
	{
		self.progressView.progress = self.progressView.progress+0.003;
	}

	
}
-(void)stopProgressViewBarRun
{
	[self.progressView setProgress:1.0];
	if (self.timer != nil) 
	{
		[self.timer invalidate];
	}
}
 
 **********/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations

    if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        self.view.frame = CGRectMake(0, 0, 320, 480);
        
        if (viewMovedUp)
        {
            CGRect rect = captionTextField.frame;
            rect.origin.y = 220;
            captionTextField.frame = rect;
        }
        
        activityIndicator.center = CGPointMake(160, 240);
    }
    else 
    {
        self.view.frame = CGRectMake(0, 0, 480, 320);        

        if (viewMovedUp)
        {
            CGRect rect = captionTextField.frame;
            rect.origin.y = 120;
            captionTextField.frame = rect;
        }
        
        activityIndicator.center = CGPointMake(240, 160);        
    }

    return YES;
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    //NSLog(@"Photo Upload viewDidUnload");
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


/****
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
	if (self.view.frame.size.width != 320.0) 
	{
		activityIndicator.frame = CGRectMake(230.0, 150.0, activityIndicator.frame.size.width,activityIndicator.frame.size.height);
	}
	else
	{
		activityIndicator.frame = CGRectMake(150.0, 230.0, activityIndicator.frame.size.width,activityIndicator.frame.size.height);
	}
    self.captionTextField.placeholder = [NSString stringWithFormat:NSLocalizedString(@"Uploaded By %@ iPhone App",@"+US give US to Translate"),[TaggedUtility taggedGetBrand]];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

}

- (void)viewDidAppear:(BOOL)animated
{
    // after the whole view is shown, we display image to be uploaded.
    mainImageView.image = selectImage;    
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    
    if (viewMovedUp)
    {
        [captionTextField resignFirstResponder];
    }  
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


// Animate the entire view up or down, to prevent the keyboard from covering the author field.
- (void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    // Make changes to the view's frame inside the animation block. They will be animated instead
    // of taking place immediately.
    CGRect rect = captionTextField.frame;
    //UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight)
    {
        if (movedUp)
        {
            rect.origin.y = 120;
        }
        else
        {
            rect.origin.y = 280 ;
        }
        
    }
    else 
    {
        if (movedUp)
        {
            rect.origin.y = 220;
        }
        else
        {
            rect.origin.y = 440;
        }
        
    }

    captionTextField.frame = rect;
    
    [UIView commitAnimations];
}

- (IBAction)clickCancel
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)clickDone
{   
//    if (viewMovedUp)
//    {
//        [captionTextField resignFirstResponder];
//    }
//    
//    [self startUploadImage];
}


-(void) startUploadImage
{
    [activityIndicator startAnimating];
    self.view.userInteractionEnabled = FALSE;
    self.navigationController.navigationBar.userInteractionEnabled = FALSE;
    
    self.caption = [captionTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (self.caption == nil || self.caption.length == 0)
    {
        self.caption = [NSString stringWithFormat:NSLocalizedString(@"Uploaded By %@ iPhone App",@"+US give US to Translate"),[TaggedUtility taggedGetBrand]];
    }
    
    // resize image as necessary
    UIImage *newImage = [TaggedUtility correctImageOrientation:selectImage withMax:960 withMin:kMinImageWidth];

    if (newImage == nil)
    {
        [activityIndicator stopAnimating];        
        self.view.userInteractionEnabled = TRUE;
        self.navigationController.navigationBar.userInteractionEnabled = TRUE;
        
        [appDelegate popAlertWithMessage:NSLocalizedString(@"Image format is not supported. Please pick a JPEG image.",@"+US give US to Translate") forView:self.navigationController.view target:nil selector:nil isAnimated:NO];
         
        return;
    }
    
    NSData *imageData = UIImageJPEGRepresentation(newImage, 0.6);
    
    [uploadConnection cancelDownload];
    self.navItem.titleView = self.progressView;
	NSMutableDictionary *option = [[NSMutableDictionary alloc] initWithObjectsAndKeys:caption, @"caption", imageData, @"imageData", nil];
    [uploadConnection startDownload :[appDelegate.taggedRequest createPhotoUploadRequest:option] :self :@selector(didEndUploadImage:)];
    
}

     
 - (void) didEndUploadImage :(TaggedAsyncConnection *)connection
{
    [activityIndicator stopAnimating];
    [self stopProgressViewBarRun];
    self.view.userInteractionEnabled = TRUE;
    self.navigationController.navigationBar.userInteractionEnabled = TRUE;
    
    if (connection.result == nil)
    {
        [self.navigationController popViewControllerAnimated:TRUE];
        return;
    }
    
    if ([(connection.result)[@"stat"] compare:@"ok" options:NSCaseInsensitiveSearch] == NSOrderedSame)
    {
        [self.uploadResult addEntriesFromDictionary:connection.result];   
        
        // cache this image
        if ((self.uploadResult)[@"result"][@"url"] != nil)
        {
            (appDelegate.taggedRequest.imageCache)[(self.uploadResult)[@"result"][@"url"]] = self.selectImage;            
        }
        
        if ((self.uploadResult)[@"result"][@"thumb"] != nil)
        {
            (appDelegate.taggedRequest.imageCache)[(self.uploadResult)[@"result"][@"thumb"]] = self.selectImage;            
        }
        
        if (delegate != nil && [delegate respondsToSelector:@selector(photoDidUpload:)]) 
        {
            [delegate photoDidUpload:self];
        }
        // Upload new photo, so we need to update session User's photo gallery.
        NSString * sessionUserId = [TaggedUtility readString:(appDelegate.taggedRequest.sessionData)[@"user_id"]];
        NSDictionary * notificationInfo = [[NSDictionary alloc] initWithObjectsAndKeys:sessionUserId,@"user_id",nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"UpdatePhotoGalleryNotification" object:nil userInfo:notificationInfo];
       
    }
    [self.navigationController popViewControllerAnimated:TRUE];
}
    *********/
//#pragma mark -
//#pragma mark Responding to keyboard events
//
//- (void)keyboardWillShow:(NSNotification *)notification {
//    /*
//     Reduce the size of the text view so that it's not obscured by the keyboard.
//     Animate the resize so that it's in sync with the appearance of the keyboard.
//     */
//    NSDictionary *userInfo = [notification userInfo];
//    
//    // Get the origin of the keyboard when it's displayed.
//    NSValue* aValue = userInfo[UIKeyboardFrameEndUserInfoKey];
//	
//    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
//    CGRect keyboardRect = [aValue CGRectValue];
//    // This UIKeyboardBoundsUserInfoKey returns CGRect won't be auto adapt to the interface orientation changes
//	// We should exchange the width and height manually
//	if (keyboardRect.size.width < keyboardRect.size.height) 
//	{
//		float tempHeight = keyboardRect.size.height;
//		keyboardRect.size.height = keyboardRect.size.width;
//		keyboardRect.size.width = tempHeight;
//	}
//    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. 
//	//The bottom of the text view's frame should align with the top of the keyboard's final position.
//    CGFloat keyboardTop = self.view.frame.size.height - keyboardRect.size.height;
//	
//    CGRect textViewFrame = self.captionTextField.frame;
//	textViewFrame.origin.y = keyboardTop - textViewFrame.size.height;
//	
//	// Get the duration of the animation.
//    NSValue *animationDurationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey];
//    NSTimeInterval animationDuration;
//    [animationDurationValue getValue:&animationDuration];
//    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
//    [UIView beginAnimations:nil context:NULL];
//    [UIView setAnimationDuration:animationDuration];
//    captionTextField.frame = textViewFrame;
//    [UIView commitAnimations];
//	viewMovedUp = YES;
//}
//
//- (void)keyboardWillHide:(NSNotification *)notification {
//    
//    NSDictionary* userInfo = [notification userInfo];
//    /*
//     Restore the size of the text view (fill self's view).
//     Animate the resize so that it's in sync with the disappearance of the keyboard.
//     */
//    CGRect textViewFrame = captionTextField.frame;
//	textViewFrame.origin.y = self.view.frame.size.height - textViewFrame.size.height;
//	
//	NSValue *animationDurationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey];
//    NSTimeInterval animationDuration;
//    [animationDurationValue getValue:&animationDuration];
//    
//    [UIView beginAnimations:nil context:NULL];
//    [UIView setAnimationDuration:animationDuration];
//    captionTextField.frame = textViewFrame;
//    [UIView commitAnimations];
//	viewMovedUp = NO;
//}


@end
